<?php
// +---------------------------------------------------------------------------+
// | This file is part of the KnowledgebasePublisher package                   |
// | KnowledgebasePublisher - web based knowledgebase publisher tool           |
// |                                                                           |
// | Author:  Evgeny Leontev <eleontev@gmail.com>                              |
// | Copyright (c) 2005 Evgeny Leontev                                         |
// |                                                                           |
// | For the full copyright and license information, please view the LICENSE   |
// | file that was distributed with this source code.                          |
// +---------------------------------------------------------------------------+
 
class SettingModel extends AppModel
{

	var $tables = array('table'=>'setting', 'setting', 'setting_to_value', 'setting_input', 'priv_module');
	
	var $module_id;
	var $module_name;
	var $array_delim = ',';
	
	
	function getQuick($module_id, $setting_key = false) {
		$m = &new SettingModel();
		return $m->getSettings($module_id, $setting_key);
	}	
	
	
	function &getSettings($module_id = false, $setting_key = false) {
		
		$module_id = ($module_id) ? $module_id : $this->module_id;
		
		$sql = "
		SELECT 
			s.setting_key,
			s.input_id,
			IFNULL(sv.setting_value, s.default_value) AS value
		FROM 
			{$this->tbl->setting} s
		LEFT JOIN 
			{$this->tbl->setting_to_value} sv ON s.id = sv.setting_id
		WHERE 1
			AND s.active = 1 
			AND s.module_id = %d";
		
		$sql = sprintf($sql, $module_id);
		$result = &$this->db->Execute($sql) or die(db_error($sql));
		$rows = &$result->GetArray();
		$parser = $this->getParser();

		foreach($rows as $k => $v) {
			
			if($v['input_id'] == 1 && strpos($v['value'], $this->array_delim)) {
				$data[$v['setting_key']] = $this->_valueToArray($v['value']);
			} else {
				$data[$v['setting_key']] = $v['value'];
			}
			
			$data[$v['setting_key']] = $parser->parseReplacements($v['value']);
		}
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		//echo "<pre>"; print_r($data); echo "</pre>";		
		unset($rows);
		$data = ($setting_key) ? $data[$setting_key] : $data;
		return $data;
	}
		
	
	function getRecordsSql() {
		
		$sql = "
		SELECT 
			s.id AS name,
			s.setting_key,	
			s.messure,
			s.options,
			s.range,
			IFNULL(sv.setting_value, s.default_value) AS value,
			si.input,
			s.group_id,
			s.required
		FROM 
			({$this->tbl->setting} s,
			{$this->tbl->setting_input} si)
		
		LEFT JOIN {$this->tbl->setting_to_value} sv ON s.id = sv.setting_id
		
		WHERE s.active = 1 
		AND s.module_id = ?
		AND s.input_id = si.id
		ORDER BY s.module_id, s.group_id, s.sort_order";
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		return $sql;
	}
	
	
	function &getRecords() {
		$sql = $this->getRecordsSql();
		$result =& $this->db->Execute($sql, $this->module_id) or die(db_error($sql));
		$parser = $this->getParser();
		
		while($row = $result->FetchRow()){
			
			// here we can skip some fields
			if($parser->skipSettingDisplay($row['setting_key'])) {
				continue;
			}
			
			if($row['input'] == 'select') {
				$row['value'] = $this->_valueToArray($row['value']);
			}
			
			if($row['range']) {
				//if(strpos($row['range'], '-')) {
				//	$row['range'] = $this->_valueToOtherArray($row['range']);							
				//} else {
					$row['range'] = $this->_valueToArray($row['range']);
				//}
			}
			
			$group_id = $parser->parseGroupId($row['group_id']);
			$data[$group_id][$row['setting_key']] = $row;
		}
		
		ksort($data);
		return $data;
	}
	
	
	function getSettingInputTypes() {
		$sql = "
		SELECT s.id, si.input
		FROM 
			{$this->tbl->setting} s,
			{$this->tbl->setting_input} si
		WHERE s.active = 1 
		AND s.module_id = ?
		AND s.input_id = si.id";
		
		$result =& $this->db->Execute($sql, $this->module_id) or die(db_error($sql));
		return  $result->GetAssoc();	
	}
	
	function getSettingKeys() {
		$sql = "SELECT s.id, s.setting_key
		FROM {$this->tbl->setting} s
		WHERE s.active = 1 
		AND s.module_id = ?";
		
		$result =& $this->db->Execute($sql, $this->module_id) or die(db_error($sql));
		return  $result->GetAssoc();
	}
	
	
	function formDataToObj($values) {
		
		$keys = $this->getSettingKeys();
		foreach($values as $k => $v) {
			$values1[$keys[$k]] = $v;
		}
		
		return $values1;
	}
	
	
	
	function save($data) {
		
		require_once 'eleontev/SQL/MultiInsert.php';
		
		$input = $this->getSettingInputTypes();
		$keys  = array_flip($this->getSettingKeys());
		$parser = $this->getParser();
		
		//echo "<pre>"; print_r($data); echo "</pre>";		
		//echo "<pre>"; print_r($input); echo "</pre>";
		//echo "<pre>"; print_r($keys); echo "</pre>";
		//exit;
		
		// handle checkboxex
		foreach($keys as $setting_key => $setting_id) {
			if($input[$setting_id] == 'checkbox' && !isset($data[$setting_key])) {
				$data[$setting_key] = 0;
			}
		}
		
		// handle data
		foreach($data as $setting_id => $v) {
			if($input[$keys[$setting_id]] == 'select') {
				$v = $this->_valueToString($v);
			}
			
			// replacement goes in PageController
			$data1[$keys[$setting_id]] = array($keys[$setting_id], $parser->parseIn($setting_id, $v));
		}
		
		$ins = &new MultiInsert;
		$ins->setFields('setting_id', 'setting_value');
		$ins->setValues($data1);
		$sql = $ins->getSql($this->tbl->setting_to_value, 'REPLACE');
		$this->db->Execute($sql) or die(db_error($sql));
	}
	
	
	function setDefaultValues() {
		
		require_once 'eleontev/SQL/MultiInsert.php';
		
		$sql = "SELECT id AS setting_id, default_value AS setting_value 
		FROM {$this->tbl->setting} WHERE module_id = %d AND skip_default = 0";
		$sql = sprintf($sql, $this->module_id);
		$result = $this->db->Execute($sql) or die(db_error($sql));		
		
		$parser = $this->getParser();
		$data = array();
		foreach($result->GetArray() as $k => $v) {
			$data[$k]['setting_id'] = $v['setting_id'];
			$data[$k]['setting_value'] = $parser->parseReplacements($v['setting_value']);
		}
		
		
		$sql = MultiInsert::get("REPLACE {$this->tbl->setting_to_value} (setting_id, setting_value) VALUES ?", 
								$data);
		
		return $this->db->Execute($sql) or die(db_error($sql));
	}
	
	
	function setModuleId($module_name) {
		$sql = "SELECT id FROM {$this->tbl->priv_module} WHERE module_name = '%s'";
		$sql = sprintf($sql, $module_name);
		$result = &$this->db->Execute($sql) or die(db_error($sql));
		
		$this->module_id = $result->Fields('id');
		$this->module_name = $module_name;
	}
	
	
	function _valueToArray(&$val) {
		
		$val = explode($this->array_delim, $val);
		$new_ar = array();
		
		foreach($val as $v) {
			$new_ar[trim($v)] = trim($v);
		}
		return $new_ar;
	}
	
	
	function _valueToString($val) {
		if(is_array($val)) {
			$val = implode($this->array_delim, $val);
		}
		
		return $val; 
	}
	
	
	function _valueToOtherArray(&$val) {
	
		$val = explode($this->array_delim, $val);
		
		foreach($val as $k => $v) {
			$val[trim($k)] = explode('-', $v);
		}
		
		foreach($val as $k => $v) {
			$arr1[$val[$k][0]] = $val[$k][1];
		}
		
		return $arr1;
	}
	
	
	function getParser() {
		
		$is_file = false;
		$file[] = APP_MODULE_DIR . $this->module_name . '/SettingParser.php';
		$file[] = APP_EXTRA_MODULE_DIR . $this->module_name . '/SettingParser.php';
		$file[] = APP_MODULE_DIR . 'setting/' . $this->module_name . '/SettingParser.php';
		
		
		foreach($file as $v) {
			if(file_exists($v)) {
				require_once $v;
				$is_file = true;
				break;
			}
		}
		
		return ($is_file) ? new SettingParser($this) : new SettingParserDefault($this);
	}	
}


class SettingParserCommon
{
	
	var $replacements = array();
	
	
	function SettingParserCommon($model) {
		
		$document_root = $_SERVER['DOCUMENT_ROOT'];
		$pattern[] = '#\\\\#';
		$pattern[] = '#/{2,}#';
			
		$document_root = preg_replace($pattern, '/', $document_root);
		$document_root = preg_replace('#/$#', '', $document_root);
		$this->setReplacement('document_root', $document_root);
		
		$document_root_parent = preg_replace('#/\w+$#', '', $document_root);
		$this->setReplacement('document_root_parent', $document_root_parent);
		
		$this->model = &$model;
	}
	
	function setReplacement($key, $value) {
		$key = '[' . $key . ']';
		$this->replacements[$key] = $value;
	}
	
	function parseReplacements($value) {
		return str_replace(array_keys($this->replacements), $this->replacements, $value);
	}
	
	function parseReplacementsArray($values) {
		foreach($values as $k => $v) {
			$values[$k] = $this->parseReplacements($v);
		}
		
		return $values;
	}
	
	
	// when inserted no for default 
	function parseIn($key, $value) {
		return $value;
	}
	
	// when out
	function parseOut($key, $value) {
		return $value;
	}
	
	// when display we want to skip some values
	function skipSettingDisplay($key, $value = false) {
		return false;
	}
	
	// options parse
	function parseSelectOptions($key, $values) {
		return $values;
	}
	
	// here we can rearange resort group_id
	function parseGroupId($group_id) {
		return $group_id;
	}
	
	// any special rule to parse form field
	function parseForm($setting_key, $val, $field = false, $setting_msg = false) {
		return false;
	}	
}



class SettingParserDefault extends SettingParserCommon
{	
	

}
?>